import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { API } from '../../src/types/api/response'
import type { Dept, DeptQuery, CreateDept, UpdateDept } from '../../src/types/api/system/dept'

const Random = Mock.Random

// ------------ 常量定义 ------------
const deptStatuses = [
  { value: 0, label: '禁用' },
  { value: 1, label: '正常' }
]

const deptNames = [
  '技术部',
  '市场部',
  '销售部',
  '人事部',
  '财务部',
  '运营部',
  '研发部',
  '产品部',
  '客服部',
  '行政部'
]

// ------------ 工具函数 ------------
/**
 * 生成随机部门数据
 */
const generateRandomDept = (id: string, parentId: string | null = null): Dept => {
  const status = deptStatuses[Math.floor(Math.random() * deptStatuses.length)]
  const name = Random.pick(deptNames) + (parentId ? Random.natural(1, 3) : '')
  
  return {
    id,
    name,
    parentId,
    orderNum: Random.natural(1, 10),
    status: status.value as 0 | 1,
    createTime: Random.datetime('yyyy-MM-dd HH:mm:ss'),
    updateTime: Random.datetime('yyyy-MM-dd HH:mm:ss'),
    leader: Random.cname(),
    phone: Random.string('number', 11),
    email: Random.email(),
    hasChildren: false
  }
}

/**
 * 生成部门树
 */
const generateDeptTree = (depth: number = 3, parentId: string | null = null): Dept[] => {
  if (depth <= 0) return []
  
  const count = Random.natural(2, 4)
  return Array.from({ length: count }, (_, index) => {
    const id = parentId ? `${parentId}-${index + 1}` : String(index + 1)
    const dept = generateRandomDept(id, parentId)
    
    if (depth > 1) {
      dept.children = generateDeptTree(depth - 1, id)
      dept.hasChildren = dept.children.length > 0
    }
    
    return dept
  })
}

// ------------ 模拟数据 ------------
const depts: Dept[] = generateDeptTree()

// ------------ API 实现 ------------
/**
 * 获取部门树
 */
const getDeptTreeApi: MockMethod = {
  url: '/api/system/dept/tree',
  method: 'get',
  response: ({ query }: { query: DeptQuery }): API.Response<Dept[]> => {
    const { keyword, status } = query
    let filteredDepts = [...depts]

    if (keyword) {
      const filterByKeyword = (items: Dept[]): Dept[] => {
        return items.filter(item => {
          const match = item.name.includes(keyword)
          if (item.children) {
            item.children = filterByKeyword(item.children)
            return match || item.children.length > 0
          }
          return match
        })
      }
      filteredDepts = filterByKeyword(filteredDepts)
    }

    if (status !== undefined) {
      const filterByStatus = (items: Dept[]): Dept[] => {
        return items.filter(item => {
          const match = item.status === Number(status)
          if (item.children) {
            item.children = filterByStatus(item.children)
            return match || item.children.length > 0
          }
          return match
        })
      }
      filteredDepts = filterByStatus(filteredDepts)
    }

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: filteredDepts
    }
  }
}

/**
 * 获取部门详情
 */
const getDeptDetailApi: MockMethod = {
  url: '/api/system/dept/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<Dept | null> => {
    const findDept = (items: Dept[], id: string): Dept | null => {
      for (const item of items) {
        if (item.id === id) {
          return item
        }
        if (item.children) {
          const found = findDept(item.children, id)
          if (found) {
            return found
          }
        }
      }
      return null
    }

    const dept = findDept(depts, query.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: dept || null
    }
  }
}

/**
 * 创建部门
 */
const createDeptApi: MockMethod = {
  url: '/api/system/dept',
  method: 'post',
  response: ({ body }: { body: CreateDept }): API.Response<Dept> => {
    const newDept: Dept = {
      ...body,
      id: String(depts.length + 1),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      leader: body.leader || '',
      phone: body.phone || '',
      email: body.email || '',
      hasChildren: false
    }

    if (body.parentId) {
      const findParent = (items: Dept[]): boolean => {
        for (const item of items) {
          if (item.id === body.parentId) {
            if (!item.children) {
              item.children = []
            }
            item.children.push(newDept)
            item.hasChildren = true
            return true
          }
          if (item.children && findParent(item.children)) {
            return true
          }
        }
        return false
      }
      findParent(depts)
    } else {
      depts.push(newDept)
    }

    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newDept
    }
  }
}

/**
 * 更新部门
 */
const updateDeptApi: MockMethod = {
  url: '/api/system/dept/:id',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: UpdateDept }): API.Response<null> => {
    const updateDept = (items: Dept[]): boolean => {
      for (const item of items) {
        if (item.id === query.id) {
          Object.assign(item, {
            ...body,
            updateTime: new Date().toISOString()
          })
          return true
        }
        if (item.children && updateDept(item.children)) {
          return true
        }
      }
      return false
    }

    updateDept(depts)
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除部门
 */
const deleteDeptApi: MockMethod = {
  url: '/api/system/dept',
  method: 'delete',
  response: ({ body }: { body: { ids: string[] } }): API.Response<null> => {
    const deleteDepts = (items: Dept[]): void => {
      for (let i = items.length - 1; i >= 0; i--) {
        const item = items[i]
        if (body.ids.includes(item.id)) {
          items.splice(i, 1)
        } else if (item.children) {
          deleteDepts(item.children)
          item.hasChildren = item.children.length > 0
        }
      }
    }

    deleteDepts(depts)
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 修改部门状态
 */
const changeDeptStatusApi: MockMethod = {
  url: '/api/system/dept/:id/status',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: { status: 0 | 1 } }): API.Response<null> => {
    const updateStatus = (items: Dept[]): boolean => {
      for (const item of items) {
        if (item.id === query.id) {
          item.status = body.status
          item.updateTime = new Date().toISOString()
          return true
        }
        if (item.children && updateStatus(item.children)) {
          return true
        }
      }
      return false
    }

    updateStatus(depts)
    return {
      code: 200,
      success: true,
      message: '状态修改成功',
      data: null
    }
  }
}

// ------------ 导出 ------------
export default [
  getDeptTreeApi,
  getDeptDetailApi,
  createDeptApi,
  updateDeptApi,
  deleteDeptApi,
  changeDeptStatusApi
] as MockMethod[] 